<?php
namespace Tbf\Component\Http\Adapter;
use Symfony\Component\HttpFoundation\Request as SymfonyRequest;
use Guzzle\Http\Message\EntityEnclosingRequest as GuzzleEntityEnclosingRequest;
use Guzzle\Http\Message\Request as GuzzleRequest;
use Symfony\Component\HttpFoundation\FileBag;
use Symfony\Component\HttpFoundation\File\UploadedFile;

class GuzzleToSymfonyRequest
{
    /**
     * transform guzzle request to symfony request
     * @param  GuzzleRequest  $guzzle_request
     * @return SymfonyRequest
     */
    public function handle(GuzzleRequest $guzzle_request)
    {
        $url = $guzzle_request->getUrl(false);
        $method = $guzzle_request->getMethod();
        //url,method
        $symfony_request = SymfonyRequest::create($url, $method);
        //get data
        $query = $guzzle_request->getQuery()->getAll();
        $symfony_file_bag = new FileBag();
        $content = '';
        $post = array();
        if ($guzzle_request instanceof GuzzleEntityEnclosingRequest) {
            $guzzle_file_bag = $guzzle_request->getPostFiles();
            $content = (string) $guzzle_request->getBody();
            $post = $guzzle_request->getPostFields()->getAll();
            if (!empty($guzzle_file_bag)) {
                foreach ($guzzle_file_bag as $key=>$guzzle_file) {
                    /** @var \Guzzle\Http\Message\PostFile $guzzle_file */
                    $guzzle_file = array_pop($guzzle_file);
                    $symfony_file_bag->set($key,
                        new UploadedFile($guzzle_file->getFilename(),
                            basename($guzzle_file->getFilename()),
                            $guzzle_file->getContentType(),
                            null,null,true)
                    );
                }
            }
        }

        $server = $symfony_request->server->all();
        //content问题
        $symfony_request->initialize(
            $query,
            $post,
            $symfony_request->attributes->all(),
            $symfony_request->cookies->all(),
            $symfony_file_bag->all(),
            $server,
            $content
        );
        //header

        $header_map = $guzzle_request->getHeaders()->getAll();
        $output_header_map = array();
        foreach ($header_map as $header) {
            $name = $header->getName();
            $output_header_map[$name] = (string) $header;
        }
        $symfony_request->headers->replace($output_header_map);

        return $symfony_request;
    }
}
